﻿using System;
using System.Collections.Generic; // gerir notkun á sniðmátum möguleg
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security;
using skags.Models;


/*
* University of Reykjavík
* Brjóstagjöf.is is the product of first-year practical programming course
* for computer science students at said university
*
* URL: http://code.google.com/p/scags 
* Authors: 
* Ástvaldur Sigurðsson
* Guðjón Jónsson
* Kristín Inga Vigfúsdóttir
* Steinar Bragi Sigurðsson
* Sveinn Ernstsson
*/

namespace skags.Models
{
    /* Gagnagrunnsklasi. Föll hans sjá um að sækja og senda notendagögn inn í gagnagrunn */
    public class ProfileRepository
    {
        // tilvik af gagnagrunni (vísun/tenging í gagnagrunn) búin til
        /* Mynda tengingu við grunninn okkar */
        DBDataContext _database = new DBDataContext();

        /* Fall sem vistar breytingar ofan í grunn */
        public void Save()
        {
            _database.SubmitChanges();
        }

        /* Fall sem skilar einu barni út frá id */
        public Child GetChildByID(int id)
        {
            return _database.Childs.SingleOrDefault(u => u.ID == id);
        }

        /* Fall sem skilar nafni út frá hash id */
        public string GetNameByHashID(System.Guid id)
        {
            return _database.UserInfos.SingleOrDefault(u => u.UserID == id).FullName;
        }

        /*  Fall sem skilar id eftir username */
        public System.Guid GetHashIDByUsername(string userid)
        {
            return _database.aspnet_Users.SingleOrDefault(u => u.UserName == userid).UserId;
        }

        /*  Fall sem baetir barni við foreldra */
        public void AddChildToParent(Child child)
        {
            var uRep = new UserRepository();
            child.ParentID = uRep.GetHashIDByUsername(HttpContext.Current.User.Identity.Name);
            _database.Childs.InsertOnSubmit(child);
            Save();
        }

        /* Fall sem eyðir út barni */
        public void RemoveChild(Child childToRemove)
        {   
            // Eyðir tímalínum barnsins
            DeleteChildsTimelines(childToRemove.ID);
            // Eyðir barninu sjálfu
            _database.Childs.DeleteOnSubmit(childToRemove);
            Save();
        }
        public void DeleteChildsTimelines(int id)
        {
            var linesToDelete = (from t in _database.Timelines
                                 where t.ChildID == id
                                 select t);
            _database.Timelines.DeleteAllOnSubmit(linesToDelete);       
        }

        /* Fall sem uppfaerir persónuupplýsingar barns */
        public void UpdateChild(Child child)
        {
            var theChild = GetChildByID(child.ID);
            if (theChild != null)
            {
                theChild.Name = child.Name;
                theChild.Sex = child.Sex;
                theChild.Description = child.Description;
                theChild.BirthDate = child.BirthDate;
                Save();
            }
        }

        // Vista prófíl stillingar í gagnagrunni
        public void UpdateProfileSettings(ProfileSettingsViewModel item)
        {
            var userRep = new UserRepository();
            var theUser = userRep.GetHashIDByUsername(HttpContext.Current.User.Identity.Name);
            var records_settings = _database.PrivacySettings.SingleOrDefault(u => u.UserID == theUser);

            /*
             * Stillingar
             */

            // Ef engar stillingar eru til fyrir viðkomandi
            // Búum við þær til
            if (records_settings == null)
            {
                item.PrivacySettings.UserID = theUser;
                _database.PrivacySettings.InsertOnSubmit(item.PrivacySettings);
                Save();
            }
            // Annars uppfærum við núverandi stillingar
            else
            {
                records_settings.ShowEmail = item.PrivacySettings.ShowEmail;
                records_settings.ShowAddress = item.PrivacySettings.ShowAddress;
                records_settings.ShowNumOfChildren = item.PrivacySettings.ShowNumOfChildren;
                records_settings.ShowChildrenNames = item.PrivacySettings.ShowChildrenNames;
                records_settings.Subscription = item.PrivacySettings.Subscription;
            }

            /*
             * Upplýsingar
             */

            var records_info = (from s in _database.UserInfos
                                where s.UserID == theUser
                                select s).SingleOrDefault();

            var records_info2 = (from s in _database.UserInfos
                                 join m in _database.aspnet_Memberships on s.UserID equals m.UserId
                                 where s.UserID == theUser
                                 select m).SingleOrDefault();

            if( records_info != null && records_info2 != null )
            {
                records_info.Address = item.Info.Address;
                records_info2.Email = item.Info.Email;
                records_info2.LoweredEmail = item.Info.Email.ToLower();
                records_info.FullName = item.Info.FullName;
                records_info.FacebookUrl = item.Info.FacebookUrl;
                records_info.ZipCode = item.Info.ZipCode;
                records_info.Description = item.Info.Description;
            }

            Save();
        }
        /*Fall sem skilar öllum börnum notanda*/
        public IEnumerable<Child> GetUsersChildren()
        {
            var userRep = new UserRepository();
            var theUser = userRep.GetHashIDByUsername(HttpContext.Current.User.Identity.Name);

            var myChildren = _database.Childs.Where(s => s.ParentID == theUser);
            return myChildren;
        }

        /* Fall sem skilar öllum börnum notanda og mælingum barns út frá ID*/
        public ChildTimelineViewModel GetChildMeasurements(int? id)
        {
            var myChildren = GetUsersChildren();

            var myMeasurements = _database.Timelines.Where(s => (s.ChildID == id) && (s.OtherInfo == null));

            return new ChildTimelineViewModel { Measurements = myMeasurements, Children = myChildren };
        }
        /* Fall sem skilar öllum börnum notanda og tímalínum barns út frá ID*/
        public ChildTimelineViewModel GetChildTimelines(int? id)
        {
            var myChildren = GetUsersChildren();
            var myChild = GetChildByID(id.GetValueOrDefault());
            var myTimelines = (from s in _database.Timelines
                               where (s.ChildID == id) && (s.CHeight == null)
                               orderby s.LineDate
                               select s);

            return new ChildTimelineViewModel { Timelines = myTimelines, Children = myChildren, Child= myChild };
        }
        /* Fall sem skilar öllum tímalínum notanda skipt í tímalínur og mælingar */
        public TimelineMeasurementsViewModel GetUsersTimelines()
        {
            var userRep = new UserRepository();
            var theUser = userRep.GetHashIDByUsername(HttpContext.Current.User.Identity.Name);

            /* linq fyrirspurn - gögnum stungið í */
            var myTimelines = (from t in _database.Timelines
                               join c in _database.Childs on t.ChildID equals c.ID
                               where c.ParentID == theUser
                               orderby t.ID descending
                               select new TimelineViewModel
                               {
                                   ChildName = c.Name,
                                   ID = t.ID,
                                   CHeight = t.CHeight,
                                   CWeight = t.CWeight,
                                   LineDate = t.LineDate,
                                   OtherInfo = t.OtherInfo
                               });
            var measurements = from m in myTimelines
                               where m.OtherInfo == null
                               select m;
            var timelines = from t in myTimelines
                            where t.CHeight == null
                            select t;

            return new TimelineMeasurementsViewModel { Measurements = measurements, Timelines = timelines };

        }
        /*  Fall sem skilar tímalínu út frá ID */
        public Timeline GetTimelineById(int id)
        {
            return (from s in _database.Timelines
                    where s.ID == id
                    select s).SingleOrDefault();
        }
        /*  Fall sem baetir tímalínuhlut við barn */
        public void AddTimelineObject(Timeline timeline)
        {
            _database.Timelines.InsertOnSubmit(timeline);
            Save();
        }
        // Eyðir tímalínu
        public void DeleteTimeline(int id)
        {
            var itemToDelete = GetTimelineById(id);

            _database.Timelines.DeleteOnSubmit(itemToDelete);

            Save();
        }

        public ProfileViewModel GetProfileInfoByUserID(System.Guid userid)
        {
            var userRep = new UserRepository();

            return (from s in _database.UserInfos
                            join u in _database.aspnet_Users on s.UserID equals u.UserId
                            join m in _database.aspnet_Memberships on u.UserId equals m.UserId
                            where s.UserID == userid
                            select new ProfileViewModel
                            {
                                Info = new ProfileInfo
                                           {
                                               ID = s.ID,
                                                UserID = s.UserID,
                                            UserName = u.UserName,
                                            FullName = s.FullName,
                                            Email = m.Email,
                                            Address = s.Address,
                                            ZipCode = s.ZipCode,
                                            FacebookUrl = s.FacebookUrl,
                                            Description = s.Description
                                           },
                                ProfilePic = s.ProfilePic,
                                LastLogin = m.LastLoginDate,
                                Child = (from c in _database.Childs
                                         where c.ParentID == userid
                                         select c),
                                PrivacySettings = (from p in _database.PrivacySettings
                                         where p.UserID == userid
                                         select p).SingleOrDefault()
                            }).SingleOrDefault();
        }

        public PrivacySetting GetSettingsForUser(System.Guid user)
        {
            return _database.PrivacySettings.Where(s => s.UserID == user).SingleOrDefault();
        }

        public ProfileInfo GetInfoForUser(System.Guid userid)
        {
            var userRep = new UserRepository();

            return GetProfileInfoByUserID(userid).Info;
        }
    }
}